package com.lzw.blog.Controller;

import com.lzw.blog.vo.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.Random;

@RestController
@RequestMapping("email")
public class EmailController {

    @Value("${spring.email.host}")
    String host;

    // 发件人邮箱
    @Value("${spring.email.username}")
    String fromEmail;

    @Value("${spring.email.password}")
    String emailPassword;

    @PostMapping("/sendEmailCode")
    public Result sendEmailCode(@RequestBody EmailRequest emailRequest) {
        String email = emailRequest.getEmail();
        if (email == null || email.isEmpty()) {
            return Result.fail(400,"邮箱不能为空");
        }
        System.out.println("邮箱:" + email);
        // 生成6位验证码
//        String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
        // 将验证码放到session中，后面验证验证码时会用到
//        session.setAttribute("verifyCode", verifyCode);
        String verifyCode = String.valueOf(emailRequest.getCcode() + 5223);
        // 邮件主题
        String emailSubject = "验证码";
        // 邮件内容
        String emailContent = "您正在进行邮箱验证，您的验证码为：" + verifyCode + "，请于5分钟内完成验证！";


        // 如果是163邮箱，需要使用授权码作为密码


        // 设置邮件服务器主机名
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.auth", "true");

        // 获取默认session对象
        Session mailSession = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(fromEmail, emailPassword); // 发件人邮箱账号、授权码
            }
        });

        try {
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(mailSession);

            // Set From: 头部头字段
            message.setFrom(new InternetAddress(fromEmail));

            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));

            // Set Subject: 头部头字段
            message.setSubject(emailSubject);

            // 设置消息体
            message.setText(emailContent);

            // 发送消息
            Transport.send(message);
            System.out.println("Sent message successfully....");

            return Result.success("验证码发送成功");

        } catch (MessagingException mex) {
            mex.printStackTrace();
            return Result.success("验证码发送失败");
        }

    }

    public static String generateRandomCode(int length) {
        Random random = new Random();
        StringBuilder code = new StringBuilder();

        for (int i = 0; i < length; i++) {
            int digit = random.nextInt(10); // 生成0到9之间的随机数字
            code.append(digit);
        }

        return code.toString();
    }

    public static class EmailRequest {
        private String email;
        private Integer Ccode;

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }

        public Integer getCcode() {
            return Ccode;
        }

        public void setCcode(Integer ccode) {
            Ccode = ccode;
        }
    }
}
